<?
/*
* 中文截取，支持gb2312,gbk,utf-8,big5
*
* @param string $str 要截取的字串
* @param int $start 截取起始位置
* @param int $length 截取长度
* @param string $charset utf-8|gb2312|gbk|big5 编码
* @param $suffix 是否加尾缀
*/
function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
   if(function_exists("mb_substr")){
       if(mb_strlen($str, $charset) <= $length) return $str;
       $slice = mb_substr($str, $start, $length, $charset);
   }else{
       $re['utf-8']  = "/[/x01-/x7f]|[/xc2-/xdf][/x80-/xbf]|[/xe0-/xef][/x80-/xbf]{2}|[/xf0-/xff][/x80-/xbf]{3}/";
       $re['gb2312'] = "/[/x01-/x7f]|[/xb0-/xf7][/xa0-/xfe]/";
       $re['gbk']    = "/[/x01-/x7f]|[/x81-/xfe][/x40-/xfe]/";
       $re['big5']   = "/[/x01-/x7f]|[/x81-/xfe]([/x40-/x7e]|/xa1-/xfe])/";
       preg_match_all($re[$charset], $str, $match);
       if(count($match[0]) <= $length) return $str;
       $slice = join("",array_slice($match[0], $start, $length));
   }
   if($suffix) return $slice."…";
   return $slice;
}
/*
* 字符串长度(按个数)
*
* @param strint $str
*/
function strLength($str){
    if ($str == '') return 0;
    $count = 0;
    while (1){
        if ($str[$count] != NULL){
                $count++;
                continue;
        }else{
                break;
        }
    }
    return $count;
}
/*
* 冒泡排序（数组排序）
*
* @param array $array 排序的数组
*/

function bubble_sort($array)
{
        $count = count($array);
        if ($count <= 0) return false;
        for($i=0; $i<$count; $i++){
                for($j=$count-1; $j>$i; $j--){
                        if ($array[$j] < $array[$j-1]){
                                $tmp = $array[$j];
                                $array[$j] = $array[$j-1];
                                $array[$j-1] = $tmp;
                        }
                }
        }
        return $array;
}

/*
* 二维数组排序
*
* @param array $array 排序的数组
* @param string $sort_key 按照排序的字段
* @param string $srot_type 默认为按照通常方法比较，1按照数值比较，2按照字符串比较；
* @param string $sort_order 按照排序的顺序,SORT_ASC - 按照上升顺序排序,SORT_DESC下降顺序排序
* @param bool $is_case 不区分大小写字母排序
*/

function arrayMultiSort($array=array(),$sort_key='',$srot_type,$sort_order=SORT_DESC,$is_case=false){
    if(!count($array))return ;
    switch($srot_type){
        case 1:
            $srot_typ = SORT_NUMERIC;
            break;
        case 2:
            $srot_typ = SORT_STRING;
            break;
        default:
            $srot_type = SORT_REGULAR;
            break;
    }
    if(!$srot_type)$srot_type=SORT_REGULAR;
    if(!$sort_order)$sort_order=SORT_DESC;
    if($is_case)
        $data = array_map('strtolower', $array);
    else
        $data = $array;
    foreach ($data as $k=>$v){
        if($sort_key)
            $n[$k] = $v[$sort_key];
        else
            $n[$k] = $value;
    }
    array_multisort($n,$srot_type ,$sort_order,$data);
    return $data;
}

/**
* 根据指定的键值对数组排序
*
* @param array $array 要排序的数组
* @param string $keyname 键值名称
* @param int $sortDirection 排序方向
*
* @return array
*/
function array_column_sort($array, $keyname, $sortDirection = SORT_ASC) {
    return array_sortby_multifields($array, array($keyname => $sortDirection));
}

/**
* 从数组中删除空白的元素（包括只有空白字符的元素）
*
* @param array $arr
* @param boolean $trim
*/
function array_remove_empty(& $arr, $trim = true) {
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            array_remove_empty($arr[$key]);
        } else {
            $value = trim($value);
            if ($value == '') {
                unset($arr[$key]);
            } elseif ($trim) {
                $arr[$key] = $value;
            }
        }
    }
}
/**
* 从一个二维数组中返回指定键的所有值
*
* @param array $arr
* @param string $col
*
* @return array
*/
function array_col_values(& $arr, $col) {
    $ret = array();
    foreach ($arr as $row) {
        if (isset($row[$col])) {
            $ret[] = $row[$col];
        }
    }
    return $ret;
}
/**
* 将一个二维数组转换为 hashmap
*
* 如果省略 $valueField 参数，则转换结果每一项为包含该项所有数据的数组。
*
* @param array $arr
* @param string $keyField
* @param string $valueField
*
* @return array
*/
function array_to_hashmap(& $arr, $keyField, $valueField = null) {
    $ret = array();
    if ($valueField) {
        foreach ($arr as $row) {
            $ret[$row[$keyField]] = $row[$valueField];
        }
    } else {
        foreach ($arr as $row) {
            $ret[$row[$keyField]] = $row;
        }
    }
    return $ret;
}
/**
* 将一个二维数组按照指定字段的值分组
*
* @param array $arr
* @param string $keyField
*
* @return array
*/
function array_group_by(& $arr, $keyField) {
    $ret = array();
    foreach ($arr as $row) {
        $key = $row[$keyField];
        $ret[$key][] = $row;
    }
    return $ret;
}
/**
* 随机获取一维数组值
*
* @param array $arr
* @param string $count 获取个数
*
* @return array
*/
function randArray($arr=array(),$count=1){
    if(count($arr)<=$count)return $arr;
    $rand_keys = array_rand($arr, $count);
    $return = array();
    foreach ($rand_keys as $k=>$v){
        $return[] = $arr[$v];
    }
    return $return;
}
/**
* 对数据进行编码转换
* @param array/string $data       数组
* @param string $input     需要转换的编码
* @param string $output    转换后的编码
*/
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
    if (!is_array($data)) {
        return iconv($input, $output, $data);
    } else {
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $data[$key] = array_iconv($val, $input, $output);
            } else {
                $data[$key] = iconv($input, $output, $val);
            }
        }
        return $data;
    }
}
/**
* 将字符串转换为数组
*
* @param    string    $data    字符串
* @return    array    返回数组格式，如果，data为空，则返回空数组
*/
function string2array($data) {
    if ($data == '') return array();
    eval("\$array = $data;");
    return $array;
}
/**
* 将数组转换为字符串
*
* @param    array    $data        数组
* @param    bool    $isformdata    如果为0，则不使用new_stripslashes处理，可选参数，默认为1
* @return    string    返回字符串，如果，data为空，则返回空
*/
function array2string($data, $isformdata = 1) {
    if ($data == '') return '';
    if ($isformdata) $data = new_stripslashes($data);
    return addslashes(var_export($data, TRUE));
}

/*
* 对象转换成数组
*/
function object2Array($objParam) {
    $obj_param = ( array )$objParam;
    foreach ($obj_param as $key => $value) {
        if (is_object($value)) {
            object2Array($value);
            $obj_param [$key] = ( array )$value;
        }
    }
    return $obj_param;
}
/*
* 数组转换成对象
$array = array('name' => 'one',
               'sex' => 'two',
                           'test'=>array('a'=>'ss','dd'),
               'old' => 'three'
                          );
$arrayobject = array2Object($array);
echo $arrayobject->name;  // one
print_r(object2Array($arrayobject));
*/
function array2Object($array) {
    if (!is_array($array)) return $array;

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
        foreach ($array as $name => $value) {
            $name = strtolower(trim($name));
            if ($name) $object->$name = array2Object($value);
        }

        return $object;
    } else return FALSE;
}
/*
* 数组开头添加元素 保持原始key不变 arrayUnshift($arr, array('test'=>'4'))
*/

function arrayUnshift($arrParams, $arrAdd) {
    $arr_keys = array();
    $arr_values = array();
    $arr_add_keys = array_keys($arrAdd);
    $arr_keys = array($arr_add_keys [0]);
    $arr_values = array($arrAdd [$arr_add_keys [0]]);
    foreach ($arrParams as $key => $value) {
        array_push($arr_keys, $key);
        array_push($arr_values, $value);
    }
    $arr_result = array_combine($arr_keys, $arr_values);
    return $arr_result;
}
//多维数组转一维数组 $arr=array('123.html','456.html',array('dw.html','fl.html',array('ps.html','fw.html')),'ab.html');
function rebuild_array($arr) { //rebuild a array
    static $tmp = array();

    for ($i = 0; $i < count($arr); $i++) {
        if (is_array($arr[$i])) {
            rebuild_array($arr[$i]);
        } else {
            $tmp[] = $arr[$i];
        }
    }

    return $tmp;
}
/*
* 获取客户端ip
*/
function getClientIP() {
    if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if (@$_SERVER["HTTP_CLIENT_IP"])
    $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if (@$_SERVER["REMOTE_ADDR"])
    $ip = $_SERVER["REMOTE_ADDR"];
    else if (@getenv("HTTP_X_FORWARDED_FOR"))
    $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (@getenv("HTTP_CLIENT_IP"))
    $ip = getenv("HTTP_CLIENT_IP");
    else if (@getenv("REMOTE_ADDR"))
    $ip = getenv("REMOTE_ADDR");
    else
    $ip = "127.0.0.1";
    return $ip;
}

/*
* 获取邮箱网址
*
* @param string $email 邮箱地址
*/
function emailUrl($email){
    $url = "";
    $email_array = explode("@",$email);
    $email_hz = $email_array[1];
    switch($email_hz){
        case "163.com"://163邮箱
            $url = "mail.163.com";
        break;
        case "vip.163.com"://163vip邮箱
            $url = "vip.163.com/?b08abh1";
        break;
        case "sina.com"://新浪邮箱
            $url = "mail.sina.com.cn";
        break;
        case "sina.cn"://新浪cn邮箱
            $url = "mail.sina.com.cn/cnmail/index.html";
        break;
        case "vip.sina.com"://新浪vip邮箱
            $url = "vip.sina.com.cn";
        break;
        case "2008.sina.com"://新浪2008邮箱
            $url = "mail.2008.sina.com.cn";
        break;
        case "sohu.com"://搜狐邮箱
            $url = "mail.sohu.com";
        break;
        case "vip.sohu.com"://搜狐vip邮箱
            $url = "vip.sohu.com";
        break;
        case "tom.com"://Tom邮箱
            $url = "mail.tom.com";
        break;
        case "vip.sina.com"://Tom vip 邮箱
            $url = "vip.tom.com";
        break;
        case "sogou.com"://搜狗邮箱
            $url = "mail.sogou.com";
        break;
        case "126.com"://126邮箱
            $url = "www.126.com";
        break;
        case "vip.126.com"://126 vip 邮箱
            $url = "vip.126.com/?b09abh1";
        break;
        case "139.com"://139邮箱
            $url = "mail.10086.cn";
        break;
        case "gmail.com"://Gmail邮箱
            $url = "www.google.com/accounts/ServiceLogin?service=mail";
        break;
        case "hotmail.com"://hotmail邮箱
            $url = "www.hotmail.com";
        break;
        case "189.cn"://139邮箱
            $url = "webmail2.189.cn/webmail/";
        break;
        case "qq.com"://qq邮箱
            $url = "mail.qq.com/cgi-bin/loginpage";
        break;
        case "yahoo.com"://雅虎邮箱
            $url = "mail.cn.yahoo.com";
        break;
        case "yahoo.cn"://雅虎邮箱
            $url = "mail.cn.yahoo.com";
        break;
        case "yahoo.com.cn"://雅虎邮箱
            $url = "mail.cn.yahoo.com";
        break;
        case "21cn.com"://21cn邮箱
            $url = "mail.21cn.com";
        break;
        case "eyou.com"://eyou邮箱
            $url = "www.eyou.com";
        break;
        case "188.com"://188邮箱
            $url = "www.188.com";
        break;
        case "yeah.net"://yeah邮箱
            $url = "www.yeah.net";
        break;
        case "foxmail.com"://foxmail邮箱
            $url = "mail.qq.com/cgi-bin/loginpage?t=fox_loginpage";
        break;
        case "wo.com.cn"://联通手机邮箱
            $url = "mail.wo.com.cn/smsmail/login.html";
        break;
        case "263.net"://263邮箱
            $url = "www.263.net";
        break;
        case "x263.net"://263邮箱
            $url = "www.263.net";
        break;
        case "263.net.cn"://263邮箱
            $url = "www.263.net";
        break;
        default:
            $url = "www.hao123.com";
    }
    $title = "http://".$url;
    return $title;
}
/*
* 加密函数
*
* @param string $cleartext 要加密的明文
* @param string $privatekey 加密的密钥
*/

function code_encode($cleartext, $privatekey='yanguxing') {
    $str = strtoupper($cleartext);
    $clen = strlen($str );
    $hash = strtoupper(md5($privatekey));
    $hlen = strlen($hash);
    $data = '';
    for ($i = 0; $i < $clen; $i ++) {
        $j = intval(fmod($i, $hlen));
        $s = ord($code{$i}) + ord($hash{$j});
        $s = strtoupper(dechex($s));
        $data .= $s;
    }
    return $data;
}

/*
* 解密函数
*
* @param string $ciphertext 要解密的字符串
* @param string $privatekey 解密的密钥
*/

function code_decode($ciphertext, $privatekey='yanguxing'){
    $str= strtoupper($ciphertext);
    $clen = strlen($str);
    if (($clen % 2) != 0) {
        return false;
    }

    $hash = strtoupper(md5($privatekey));
    $hlen = strlen($hash);

    $unit = array();
    for ($i = 0; $i < $clen; $i += 2) {
        $unit[] = $code{$i} . $code{$i + 1};
    }
    $size = count($unit);

    $data = '';
    for ($i = 0; $i < $size; $i ++ ) {
         $j = intval(fmod($i, $hlen));
         $s = intval(hexdec($unit[$i])) - ord($hash{$j});
         $data .= chr($s);
     }
     return strtolower($data);
}
/*
* 无限分类
*
* @param array $data
*/
function getAllChild($data) {
    $result = array();
    foreach($data as $val) {
    //获取顶级分类
        if($val['parent_id'] == 0) {
            $val['child'] = $getChild($val['id'],$val);
            $result[] = $val;
        }
    }
    return $result;
}

/*
* 递归获取无限分类
*/
function getChild($pid, $data) {
    $result = array();
    foreach($data as $i=>$val) {
        if($val['parent_id'] == $pid) {
            $val['child'] = $this->getChild($val['id'], $data);
            $result[] = $val;
        }
    }
    return $result;
}

/**
 * 无限分类
 * 将数据格式化成树形结构
 * @author Xuefen.Tong
 * @param array $items
 * @return array
 */
function genTree9($items) {
    $tree = array(); //格式化好的树
    foreach ($items as $item)
        if (isset($items[$item['pid']]))
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        else
            $tree[] = &$items[$item['id']];
    return $tree;
}
/*
* 二维数组过滤重复
*
* @param array $arr 要过滤的数组
* @param string $key 过滤的元素名
*/
function sysSortArray($arr,$key){
    $tmp_arr = array();
    foreach($arr as $k => $v) {
        if(in_array($v[$key],$tmp_arr))
        {
            unset($arr[$k]);
        }else {
            $tmp_arr[] = $v[$key];
        }
    }
    return $arr;
}
/*
* 获取文件后缀名
*
* @param string $file 文件名
*/
function getFileExtensions($file=''){
    if(function_exists('strrchr')){
        $filename = strrchr($file, ".");
    }else{
        $filename = '.'.pathinfo($url,PATHINFO_EXTENSION);
    }
    return $filename;
}
/*
* 去除文件后缀名
*
* @param string $file 文件名
*/
function getFileName($file=''){
    return str_replace(strrchr($file, "."),"",$file);
}
/*
* 重命名文件
*
* @param string $source 源文件
* @param string $dest 目标文件
*/
function file_rename($source,$dest){
    if(PHP_OS=='WINNT'){
        @copy($source,$dest);
        @unlink($source);
        if(file_exists($dest)) return true;
        else return false;
    }else{
        return rename($source,$dest);
    }
}
/*
* 删除目录
*
* @param string $dir 文件夹目录路径
*/
function deleteDir($dir){
    $handle = @opendir($dir);
    if(!$handle){
        die("目录不存在");
    }
    while (false !== ($file = readdir($handle))) {
        if($file != "." && $file != ".."){
            $file = $dir . DIRECTORY_SEPARATOR .$file;
            if (is_dir($file)){
                deleteDir($file);
            } else {
                @unlink($file);
            }
        }
    }
    closedir( $handle );
    @rmdir($dir);
}
/*
* 检查上传源文件名是否合法
*
* @param string $filename 文件名
* @param string $type 判断类型
*/
function ext_valid($filename,$type)
{
    $extarr = array();
    $filename = strtolower($filename);
    $extarr[0]= array(".gif",".jpg",".jpeg",".png");
    if(!isset($extarr[$type])) return false;
    if($ext = strrchr($filename,"."))
    {
        if(in_array($ext,$extarr[$type]))
        {
            return true;
        }else return false;
    }
    else return false;
}
/*
* 获取时间天数
*
* @param string $time 时间
*/
function timeLength($time){
    if($day = floor($time/(24*3600))){
        $length .= $day.'天';
    }
    if($hour = floor($time % (24*3600)/3600)){
        $length .= $hour.'小时';
    }
    if($day==0 && $hour==0){
        $length = floor($time/60).'分';
    }
    return $length;
}
/*
* 时间格式化
*
* @param string $timestamp 时间戳
* @param string $format 格式类型
*/
function time_format($timestamp,$format = TIME_SHORT){
    switch($format){
    case TIME_SHORT:
        return date('n/j H:m',$timestamp);
    case TIME_LANG:
        return date('D M j',$timestamp);
    default:
        return date('j/n/Y',$timestamp);
    }
}
/*
* 获取某月的最后一天
*
* @param string $timestamp 时间戳或者格式
* @param return Y-m-d 格式类型
*/
function getMonthLastDay($timestamp=''){
    if(empty($timestamp))
        $timestamp = strtotime(date('Y-m'));
    else{
        if(!is_numeric($timestamp))
        $timestamp = strtotime($timestamp);
    }
    $firstday = date('Y-m-01', $timestamp);
    return date('Y-m-d', strtotime("$firstday +1 month -1 day"));
}

function numberorzh($n=''){
    if(empty($n))return;
    $n = round($n, 2);
    $n = $n * 100;
    $n = (string)$n;
    $z = array('分','角','元','拾','佰','仟','万','拾','佰','仟','亿','拾','佰','仟','万亿');
    $c = array(0=>'零',1=>'壹',2=>'贰',3=>'叁',4=>'肆',5=>'伍',6=>'陆',7=>'柒',8=>'捌',9=>'玖');
    $count = strlen($n);
    for($i=0;$i<$count;$i++){
        if($count-$i)
        $r .= $c[$n[$i]].$z[$count-$i-1];
    }
    return $r;
}
$items = array(
    1 => array('id' => 1, 'pid' => 0, 'name' => '江西省'),
    2 => array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'),
    3 => array('id' => 3, 'pid' => 1, 'name' => '南昌市'),
    4 => array('id' => 4, 'pid' => 2, 'name' => '哈尔滨市'),
    5 => array('id' => 5, 'pid' => 2, 'name' => '鸡西市'),
    6 => array('id' => 6, 'pid' => 4, 'name' => '香坊区'),
    7 => array('id' => 7, 'pid' => 4, 'name' => '南岗区'),
    8 => array('id' => 8, 'pid' => 6, 'name' => '和兴路'),
    9 => array('id' => 9, 'pid' => 7, 'name' => '西大直街'),
    10 => array('id' => 10, 'pid' => 8, 'name' => '东北林业大学'),
    11 => array('id' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'),
    12 => array('id' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'),
    13 => array('id' => 13, 'pid' => 1, 'name' => '赣州市'),
    14 => array('id' => 14, 'pid' => 13, 'name' => '赣县'),
    15 => array('id' => 15, 'pid' => 13, 'name' => '于都县'),
    16 => array('id' => 16, 'pid' => 14, 'name' => '茅店镇'),
    17 => array('id' => 17, 'pid' => 14, 'name' => '大田乡'),
    18 => array('id' => 18, 'pid' => 16, 'name' => '义源村'),
    19 => array('id' => 19, 'pid' => 16, 'name' => '上坝村'),
);
/**
 * @desc 生成n个随机手机号
 * @param int $num 生成的手机号数
 * @author niujiazhu
 * @return array
 */
function randMobile($num = 1){
    //手机号2-3为数组
    $numberPlace = array(30,31,32,33,34,35,36,37,38,39,50,51,58,59,89);
    for ($i = 0; $i < $num; $i++){
        $mobile = 1;
        $mobile .= $numberPlace[rand(0,count($numberPlace)-1)];
        $mobile .= str_pad(rand(0,99999999),8,0,STR_PAD_LEFT);
        $result[] = $mobile;
    }
    return $result;
}
/**
 * @desc 随机生成小数
 * @param int $num 小数点位数
 * @author niujiazhu
 * @return string
 */
function randomFloat($min = 0, $max = 2,$num=1) {
	return round($min + mt_rand() / mt_getrandmax() * ($max - $min),$num);
}
//print_r(genTree9($items));

/**
 * @导出csv
 * $csv_data = array(array('Name', 'Address'),array('张三','深圳'));
 * exportToCsv($csv_data,'new_file.csv');
 * $filename 文件名
 */
function exportToCsv($csv_data, $filename = 'export.csv') {
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    // Gets the data from the database
    $schema_insert = '';
    $out = '';
    // Format the data
    foreach ($csv_data as $row)
    {
        $schema_insert = '';
        $fields_cnt = count($row);
        //printr($row);
        $tmp_str = '';
        foreach($row as $v)
        {
            $tmp_str .= $csv_enclosed.str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $v).$csv_enclosed.$csv_separator;
        } // end for

        $tmp_str = substr($tmp_str, 0, -1);
        $schema_insert .= $tmp_str;
        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    header("Content-type: text/x-csv");
    header("Content-Disposition:filename=$filename");
    echo $out;
}
// 检查字符串是否是UTF8编码,是返回true,否则返回false
function is_utf8($string){
	if( !empty($string) ) {
		$ret = json_encode( array('code'=>$string) );
		if( $ret=='{"code":null}') {
			return false;
		}
	}
	return true;
}

// 自动转换字符集 支持数组转换
function auto_charset($fContents,$from='gbk',$to='utf-8'){
    $from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
    $to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
    if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if(is_string($fContents) ) {
        if(function_exists('mb_convert_encoding')){
            return mb_convert_encoding ($fContents, $to, $from);
        }elseif(function_exists('iconv')){
            return iconv($from,$to,$fContents);
        }else{
            return $fContents;
        }
    }
    elseif(is_array($fContents)){
        foreach ( $fContents as $key => $val ) {
            $_key =     auto_charset($key,$from,$to);
            $fContents[$_key] = auto_charset($val,$from,$to);
            if($key != $_key )
                unset($fContents[$key]);
        }
        return $fContents;
    }
    else{
        return $fContents;
    }
}

// 浏览器友好的变量输出
function dump($var, $exit=false){
	$output = print_r($var, true);
	$output = "<pre>" . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
	echo $output;
	if($exit) exit();
}
/**
 * @json_encode
 * 由于php的json扩展自带的函数json_encode会将汉字转换成unicode码
 * 该函数不会将汉字转换为unicode码
 */
function JsonEncode($a = false) {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a)) {
        if (is_float($a)) {
            // Always use "." for floats.
            return floatval(str_replace(",", ".", strval($a)));
        }

        if (is_string($a)) {
            static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
            return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
        } else {
            return $a;
        }
    }

    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
        if (key($a) !== $i) {
            $isList = false;
            break;
        }
    }

    $result = array();
    if ($isList) {
        foreach ($a as $v) $result[] = JsonEncode($v);
        return '[' . join(',', $result) . ']';
    } else {
        foreach ($a as $k => $v) $result[] = JsonEncode($k).':'.JsonEncode($v);
        return '{' . join(',', $result) . '}';
    }
}
/**
 * 计算字符串字数
 */
function ccStrLen($str){
    $ccLen=0;
    $ascLen=strlen($str);
    $ind=0;
    $hasCC=ereg("[xA1-xFE]",$str); #判断是否有汉字
    $hasAsc=ereg("[x01-xA0]",$str); #判断是否有ASCII字符
    if($hasCC && !$hasAsc){
        return strlen($str)/2;
    }
    if(!$hasCC && $hasAsc){
        return strlen($str);
    }
    for($ind=0;$ind<$ascLen;$ind++){
        if(ord(substr($str,$ind,1))>0xa0){
            $ccLen++;
            $ind++;
        }else{
            $ccLen++;
        }
    }
    return $ccLen;
}
/**
 * 删除指定数组元素方法
 */
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE){
    $key = array_search($deleteIt,$array,TRUE);
    if($key === FALSE)
        return FALSE;
    unset($array[$key]);
    !$useOldKeys && $array = array_values($array);
    return TRUE;
}

/*
 * 防刷机制
*
* @param int $id
* @param string $time 时间戳
* @param string $type 动作方法
* @param int $num 可以刷新次数
*/
function antibrush($id,$time=3600,$type='',$num=1,$ip='127.0.0.1'){
    $ip = str_replace('.','',$ip);
    $name = $id.$type.$ip.$num.$time;
    if(empty($name)) return false;
    $lasttime = get_cookie($name,'QQEWM',2);
    if(empty($lasttime)){
        set_cookie($name, time(), $time,'QQEWM',1);
        return true;
    }elseif ($lasttime<$time+time()){
        return false;
    }
    return true;
}
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
	$type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = ip2long($ip);
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/*
 * 判断手机访问
 */

function is_mobile() {
    if (isset($_SERVER['HTTP_VIA'])) return true;
    if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) return true;
    if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) return true;
    if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0) {
        // Check whether the browser/gateway says it accepts WML.
        $br = "WML";
    } else {
        $browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
        if(empty($browser)) return true;
        $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
        $found_mobile=checkSubstrs($mobile_os_list,$browser) ||
        checkSubstrs($mobile_token_list,$browser);
        if($found_mobile)
            $br ="WML";
        else $br = "WWW";
    }
    if($br == "WML") {
        return true;
    } else {
        return false;
    }
}

/**
 * @param $time 时间戳
 * 友好时间
 * return string
 */
function fdate($time) {
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}

/**
 * 友好时间
 */
function fdate($time) {
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}

/**
 * 加密解密函数
 * @operation ENCODE:加密 DECODE:解密
 * @key 密钥
 * @expiry
 */
function authcode($string, $operation = 'ENCODE', $key = 'SAITE', $expiry = 0) {

    $ckey_length = 4; // 随机密钥长度 取值 0-32;
    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时，则不产生随机密钥
    $key = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
?>